<template>
  <div class="app-container main">
    <div>
      <el-menu :default-active="activeIndex" mode="horizontal" @select="handleSelect">
        <el-menu-item index="1">账号中心</el-menu-item>
        <el-menu-item index="2">角色中心</el-menu-item>
        <el-menu-item index="3">包裹中心</el-menu-item>
        <el-menu-item index="4">装备中心</el-menu-item>
        <el-menu-item index="5">宠物中心</el-menu-item>
      </el-menu>
    </div>
    <!-- 查询 -->
    <div id="showSearch" v-if="showSearch">
      <el-form :model="queryParams" :inline="true" size="mini" @submit.native.prevent="getList">
        <el-form-item label="上传时间：">
          <el-date-picker v-model="queryParams.start_time" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="选择开始时间"
            style="width: auto; margin-right: 0;"></el-date-picker>
          至
          <el-date-picker v-model="queryParams.end_time" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="选择结束时间"
            style="width: auto;"></el-date-picker>
        </el-form-item>
        <el-form-item label="运行状态：">
          <el-select v-model="queryParams.user_status" placeholder="请选择">
            <el-option label="全部" value="全部"></el-option>
            <el-option label="已完成" value="已完成"></el-option>
            <el-option label="运行中" value="运行中"></el-option>
            <el-option label="隔离" value="隔离"></el-option>
            <el-option label="已完成+运行中" value="已完成+运行中"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备名：">
          <el-input v-model="queryParams.user_device_name" placeholder="设备名" style="width: auto;"></el-input>
        </el-form-item>
        <el-form-item label="游戏账号：">
          <el-input v-model="queryParams.user_account" placeholder="游戏账号" style="width: auto;"></el-input>
        </el-form-item>
        <el-form-item label="游戏区：">
          <el-input v-model="queryParams.user_zone_name" placeholder="游戏区" style="width: auto;"></el-input>
        </el-form-item>
        <el-form-item label="门派：">
          <el-input v-model="queryParams.user_sect" placeholder="门派" style="width: auto;"></el-input>
        </el-form-item>
        <el-form-item label="等级：">
          <el-dropdown @command="handleLevelCommand">
            <!-- <span class="el-dropdown-link">
            {{ queryParams.user_level1 || '请选择' }}<i class="el-icon-arrow-down el-icon--right"></i>
          </span> -->
            <el-button>
              {{ queryParams.user_level1 || '请选择' }}<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command=">=">>=</el-dropdown-item>
              <el-dropdown-item command="=">=</el-dropdown-item>
              <el-dropdown-item command="<=">&lt;=</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-input v-model="queryParams.user_level2" placeholder="等级" style="width: 60px;"></el-input>
        </el-form-item>
        <el-form-item label="活跃度：">
          <el-dropdown @command="handleActivityCommand">
            <el-button class="el-dropdown-link">
              {{ queryParams.user_activity1 || '' }}<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command=">=">>=</el-dropdown-item>
              <el-dropdown-item command="=">=</el-dropdown-item>
              <el-dropdown-item command="<="> &lt;= </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-input v-model="queryParams.user_activity2" placeholder="活跃度" style="width: 60px;"></el-input>
        </el-form-item>
        <el-form-item label="金币：">
          <el-dropdown @command="handleGoldCoinCommand">
            <el-button class="el-dropdown-link">
              {{ queryParams.user_gold_coin1 || '' }}<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command=">=">>=</el-dropdown-item>
              <el-dropdown-item command="=">=</el-dropdown-item>
              <el-dropdown-item command="<=">&lt;=</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-input v-model="queryParams.user_gold_coin2" placeholder="金币" style="width: 60px;"></el-input>
        </el-form-item>
        <!-- <el-form-item>
          <el-checkbox v-model="queryParams.notgl" @change="getList" true-label="notgl" false-label="">排除隔离号</el-checkbox>
          <el-checkbox v-model="queryParams.orderByCoinr" true-label="orderByCoinr" false-label=""
            @change="getList">按金币从大到小排序</el-checkbox>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" @click="getList" style="width: 100%;">查询数据</el-button>
        </el-form-item>
        <!-- <el-form-item label="全局关键字查询：">
          <el-input v-model="queryParams.keywords" placeholder="关键字" style="width: 120px;margin-right: 10px;"></el-input>
          <el-button type="primary" @click="getList">查询</el-button>
        </el-form-item> -->
      </el-form>
    </div>
    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
        <el-button
          type="success"
          icon="el-icon-upload"
          size="mini"
          @click="handleUpload"
          >导入</el-button
        >
      </el-col>
    </el-row> -->
    <div class="flex justify-between p-10">
      <div>
        <el-button size="mini" icon="el-icon-coin">总金币:{{ TotalGoldCoin }}</el-button>
        <el-button size="mini" icon="el-icon-coin">本页金币:{{ PageGoldCoin }}</el-button>
        <el-button size="mini" icon="el-icon-coin">选中金币：{{ selectCoinNum }}</el-button>
      </div>
      <div>
        <el-button size="mini" icon="el-icon-search" @click="showSearch = !showSearch">搜索</el-button>
        <el-popover placement="bottom" width="200" trigger="click">
          <el-checkbox-group v-model="visibleColumns">
            <el-checkbox v-for="column in columns" :key="column.prop" :label="column.prop">{{ column.label
            }}</el-checkbox>
          </el-checkbox-group>
          <el-button slot="reference" size="mini" icon="el-icon-setting" class="ml-10">设置显示列</el-button>
        </el-popover>
        <el-popover placement="bottom" width="200" trigger="click">

          <el-checkbox v-model="isWan" @change="toggleWan">货币单位：万</el-checkbox>
          <el-button slot="reference" size="mini" icon="el-icon-setting" class="ml-10">设置</el-button>
        </el-popover>
        <el-dropdown @command="handleExport">
          <el-button size="mini" icon="el-icon-download" class="ml-10">导出CSV</el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="all">所有导出</el-dropdown-item>
            <el-dropdown-item command="current">本页导出</el-dropdown-item>
            <el-dropdown-item command="selected">选中导出</el-dropdown-item>

          </el-dropdown-menu>
        </el-dropdown>
        <el-button size="mini" icon="el-icon-delete" @click="delSelect" class="ml-10">删除</el-button>
        <el-button size="mini" icon="el-icon-refresh" @click="resetRefreshCountdown()" class="ml-10">刷新（{{ seconed
        }}）</el-button>

      </div>

    </div>
    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="displayData" style="width: 100%;" @selection-change="handleSelectionChange"
      highlight-current-row height="calc(100vh - 300px)">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column v-for="column in visibleColumnsMap" :key="column.label" :prop="column.prop" :label="column.label"
        align="center" :width="column.width" sortable>

        <template slot-scope="scope">
          <div v-if="column.prop == 'comment'" class="flex align-center"> {{ scope.row.comment }} <i
              class="el-icon-edit-outline" @click="handleComment(scope.row)"></i></div>
          <div v-else>
            {{ scope.row[column.prop] }}
          </div>
        </template>
      </el-table-column>
      <el-table-column v-if="isStatusVisible" align="center" prop="user_status" sortable label="状态" fixed="right">

        <template slot-scope="scope">
          <el-tag v-if="scope.row.user_status === '隔离'" type="danger" size="mini">{{ scope.row.user_status }}</el-tag>
          <el-tag v-else-if="scope.row.user_status === '运行中'" type="success" size="mini">{{ scope.row.user_status
          }}</el-tag>
          <el-tag v-else-if="scope.row.user_status === '已完成'" type="info" size="mini">{{ scope.row.user_status }}</el-tag>
        </template>
      </el-table-column>

    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.pagenum"
      @pagination="getList" />

    <!-- 修改备注 -->
    <el-dialog title="修改备注" :visible.sync="commentDialogVisible" width="30%">

      <el-input v-model="commentForm.commentVal" type="text" :rows="5" placeholder="请输入备注内容"></el-input>
      <div slot="footer" class="dialog-footer">
        <el-button @click="commentDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleCommentSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { doQuery, doDel, doComment } from "@/api/count";

import { mapGetters } from "vuex";
import { parseTime } from "@/utils";
import UploadExcelComponent from "@/components/UploadExcel/index.vue";

export default {
  name: "count",
  components: { UploadExcelComponent },

  data() {


    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 表格数据
      dataList: [],
      originalData: [], // 存储原始数据
      displayData: [], // 显示的数据
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        page: 1,
        pagenum: 50,
        user_status: '',
        user_gold_coin1: '>=',
        user_gold_coin2: '',
        user_activity1: '>=',
        user_activity2: '',
        user_device_name: '',
        user_account: '',
        user_zone_name: '',
        user_sect: '',
        user_level1: '>=',
        user_level2: '',
        start_time: '2021-06-01 00:00:00',
        end_time:parseTime(new Date()),
        keywords: '',
        notgl: '',
        orderByCoinr: '',
        use_wan_unit: false,

      },
      // 表单参数
      form: {},
      // 表单校验

      columns: [
        { prop: 'id', label: '数据ID', width: '100' },
        { prop: 'comment', label: '备注', width: '120' },
        { prop: 'user_device_name', label: '设备名', width: '120' },
        { prop: 'user_account', label: '游戏账号', width: '220' },
        { prop: 'user_password', label: '密码', width: '100' },
        { prop: 'user_zone_name', label: '游戏区角色', width: '150' },
        { prop: 'user_role', label: '角色', width: '100' },
        { prop: 'user_sect', label: '门派', width: '100' },
        { prop: 'user_level', label: '等级', width: '80' },
        { prop: 'user_name', label: '名字', width: '100' },
        { prop: 'user_gold_coin', label: '金币', width: '100' },
        { prop: 'gold_coin_growth', label: '金币涨幅', width: '100' },
        { prop: 'user_frozen_coin', label: '冻结金币', width: '120' },
        { prop: 'user_cbgfrozen_coin', label: '藏宝阁冻结金币', width: '120' },
        { prop: 'user_fairy_jade', label: '仙玉', width: '120' },
        { prop: 'user_silver_coin', label: '银币', width: '120' },
        { prop: 'user_activity', label: '活跃度', width: '90' },
        { prop: 'user_backpack_treasures', label: '背包装备珍品', width: '120' },
        { prop: 'user_backpack_simple', label: '背包装备简易', width: '120' },
        { prop: 'user_pet_life', label: '宠物寿命', width: '120' },
        { prop: 'user_backpack _full', label: '背包已满', width: '120' },
        { prop: 'user_stall_face', label: '摆摊人脸', width: '120' },
        { prop: 'user_sacred_pouch', label: '神兜兜', width: '120' },
        { prop: 'user_gem_hammer', label: '宝石锤', width: '120' },
        { prop: 'user_magic_shard', label: '法宝碎片', width: '120' },
        { prop: 'user_recharge_gear', label: '充值档位', width: '120' },
        { prop: 'user_lock_condition', label: '安全锁状态', width: '120' },
        { prop: 'user_home_degree', label: '家园环境度', width: '120' },
        { prop: 'user_home_level', label: '家园等级', width: '120' },
        { prop: 'user_qcjm_progress', label: '前尘旧梦进度', width: '120' },
        { prop: 'user_energy', label: '活力', width: '120' },
        { prop: 'user_role_scoring', label: '角色评分', width: '120' },
        { prop: 'user_double_point', label: '双倍点', width: '120' },
        { prop: 'user_function', label: '执行功能', width: '120' },
        { prop: 'user_ip', label: 'IP', width: '120' },
        { prop: 'user_imei', label: 'IMEI', width: '120' },
        { prop: 'user_status', label: '状态', width: '100' },
        { prop: 'user_run_time', label: '运行时间', width: '180' },
        { prop: 'user_last_time', label: '开始时间', width: '180' },
        { prop: 'user_start_time', label: '结束时间', width: '180' },
        { prop: 'user_end_time', label: '上传时间', width: '180' }
      ],
      visibleColumns: [
        'user_device_name',
        'user_account',
        'user_zone_name',
        'user_role',
        'user_level',
        'user_gold_coin',
        'gold_coin_growth',
        'user_activity',
        'user_last_time',
        'user_status',
        'user_name',
        'user_run_time'
      ],
      selectCoinNum: 0,
      TotalGoldCoin: 0,
      PageGoldCoin: 0,
      showSearch: false,
      activeIndex: '1',
      multipleSelection: [],
      isWan: false,
      originalTotalGoldCoin: 0,
      originalPageGoldCoin: 0,
      seconed: 30,
      refreshInterval: null,
      commentDialogVisible: false,
      commentForm: {
        id: '',
        commentVal: ''
      },

    };
  },
  computed: {
    visibleColumnsMap() {
      return this.columns.filter(column => this.visibleColumns.includes(column.prop) && column.prop !== 'user_status');
    },
    isStatusVisible() {
      return this.visibleColumns.includes('user_status');
    },

  },
  created() {
    this.getList();
    this.startRefreshCountdown();
  },
  methods: {
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      doQuery(this.queryParams).then((response) => {
        this.originalData = response.Data; // 存储原始数据
        this.originalTotalGoldCoin = response.TotalGoldCoin;
        this.originalPageGoldCoin = response.PageGoldCoin;
        this.updateDisplayData(); // 更新显示数据
        this.total = response.Total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },

    handleLevelCommand(command) {
      this.queryParams.user_level1 = command;
    },
    handleActivityCommand(command) {
      this.queryParams.user_activity1 = command;
    },
    handleGoldCoinCommand(command) {
      this.queryParams.user_gold_coin1 = command;
    },
    // 选中
    handleSelectionChange(val) {
      this.multipleSelection = val;
      let num = 0;// 选中金币
      val.forEach(e => {
        num += Number(e.user_gold_coin);

      });
      if (this.isWan) {
        num = (num / 10000).toFixed(2);
        num += 'w'

      } else {
        num = num.toLocaleString();
      }

      this.selectCoinNum = num.toLocaleString();
    },
    handleSelect(key, keyPath) {
      console.log(key, keyPath);
      if (key != '1') {
        this.$message('功能开发中');
        return
      }
    },
    updateDisplayData() {
      this.displayData = this.originalData.map(item => ({
        ...item,
        user_gold_coin: this.isWan ? ((item.user_gold_coin / 10000).toFixed(2)) + 'w' : item.user_gold_coin,
        user_silver_coin: this.isWan ? ((item.user_silver_coin / 10000).toFixed(2)) + 'w' : item.user_silver_coin,
      }));
      if (this.isWan) {
        this.TotalGoldCoin = ((this.originalTotalGoldCoin / 10000).toFixed(2)) + 'w';
        this.PageGoldCoin = ((this.originalPageGoldCoin / 10000).toFixed(2)) + 'w';
      } else {
        this.TotalGoldCoin = this.originalTotalGoldCoin.toLocaleString();
        this.PageGoldCoin = this.originalPageGoldCoin.toLocaleString();
      }
    },
    toggleWan(isWan) {
      this.isWan = isWan;
      this.updateDisplayData();
    },
    // 导出
    handleExport(command) {
      console.log(command);
      let selectedIds = this.multipleSelection.map(item => item.id);
      console.log(selectedIds);
      if (selectedIds.length == 0&&command=='selected') {
        this.$message('请选择要导出的数据');
      }
      doQuery({
        ...this.queryParams,
        exportType: command,
        selectedIds: selectedIds.join(',')
      }).then(response => {
        if (response) {
          // console.log('导出成功', response);
          // this.downloadFile(response);
          const url = window.URL.createObjectURL(new Blob([response]));
          const link = document.createElement('a');
          link.href = url;
          const fileName = command + '-' + parseTime(new Date()) + '.csv'
          link.setAttribute('download', fileName); // 设置下载文件名
          document.body.appendChild(link);
          link.click();
          link.remove();
          window.URL.revokeObjectURL(url);
        } else {
          console.error('导出失败', response.Msg);
        }
      })
        .catch(error => {
          console.error('请求失败', error);
        });
    },
    delSelect() {
      let selectedIds = this.multipleSelection.map(item => item.id);
      if (selectedIds.length == 0) {
        this.$message('请选择要删除的数据');
      } else {
        this.$confirm('是否删除选中数据?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          doDel({
            selectedIds: selectedIds.join(',')
          }).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getList();
          })
        })
      }
    },
    onReresh() {
      console.log('onReresh');
      this.getList();
    },
    startRefreshCountdown() {
      console.log("start");
      this.refreshInterval = setInterval(() => {
        if (this.seconed > 0) {
          this.seconed--;
        } else {
          this.onReresh();
          this.seconed = 30;
        }
      }, 1000);
    },
    resetRefreshCountdown() {
      this.onReresh();
      clearInterval(this.refreshInterval);
      this.seconed = 30;
      this.startRefreshCountdown();
    },
    // 修改备注
    handleComment(row) {
      this.commentForm.id = row.id
      this.commentDialogVisible = true;
    },
    handleCommentSubmit() {
      doComment(this.commentForm).then(response => {
        this.commentDialogVisible = false;
        this.resetRefreshCountdown();
      });
    },
  },
  beforeDestroy() {
    clearInterval(this.refreshInterval);
  },
};
</script>
<style scoped>
#showSearch {
  background-color: rgb(243, 248, 254);
  padding: 10px;
}

.el-form-item--mini.el-form-item,
.el-form-item--small.el-form-item {
  margin-bottom: 5px;
}

/* 新增样式，防止单元格内容换行 */
/* .no-wrap {
  white-space: nowrap;
} */

/* ::v-deep .el-table .cell {
  white-space: nowrap !important;
  overflow: visible !important;
  text-overflow: initial;
  } */
/* ::v-deep .el-table td,
.el-table th {
  padding: 5px 0;
} */

::v-deep .el-button {
  font-weight: normal;
}
</style>
